<?php

namespace App\store\services;

use App\common\models\Coupon;
use App\common\models\CouponStore;
use App\common\models\CouponUseLog;
use App\Exceptions\InvalidRequestException;
use http\Exception\InvalidArgumentException;
use Illuminate\Support\Facades\DB;

class CouponServices
{




    /**
     * 专用券首页数据
     *
     * @param $data
     * @return array
     */
    public static function specialCoupon($data)
    {
        $page = !isset($data['page']) ? 1 : $data['page'];
        unset($data['page']);
        $limit = !isset($data['limit']) ? 20 : $data['limit'];
        unset($data['limit']);

        $where_data = [];
        $where_data[] = ['type', '=', Coupon::TYPE_DEDICATED];
        $where_data[] = ['is_deleted', '=', Coupon::NOT_DELETE];
        $where_data[] = ['shop_id', '=', $data['store_id']];
        $select = ['id', 'name', 'coupon_type', 'category', 'satisfy_money', 'remitted_money', 'confine_type', 'confine_id', 'except_type', 'except_id', 'use_time_end', 'stock', 'content'];

        $list = Coupon::listed($page, $limit, $where_data, $select);

        foreach($list['data'] as $v){
            $v->use_time_end = empty($v->use_time_end) ? '' : date('Y-m-d', $v->use_time_end);
            //购买数量 已用数量
            $v->send_number = CouponUseLog::getUseNumber(['coupon_id' => $v->id]);
            $v->use_number = CouponUseLog::getUseNumber(['coupon_id' => $v->id, 'is_use' => 1]);

            //转化营业额
            $v->turnover = 0;
        }
        return $list;
    }

    /**
     * 可购买引流券列表
     *
     * @param $data
     * @return array
     */
    public static function canBuyITCouponList($data)
    {
        $page = !isset($data['page']) ? 1 : $data['page'];
        unset($data['page']);
        $limit = !isset($data['limit']) ? 10 : $data['limit'];
        unset($data['limit']);

        $where_data = [];
        $where_data[] = ['is_deleted', '=', Coupon::NOT_DELETE];
        $select = ['id', 'name', 'coupon_type', 'category', 'satisfy_money', 'remitted_money', 'use_limit_max', 'price', 'content'];

        $list = Coupon::listed($page, $limit, $where_data, $select);

        return $list;
    }

    /**
     * 引流券总计
     *
     * @param $data
     * @return array
     *
     */
    public static function myITCouponTotal($data)
    {
        //
        return ['send_number' => 0, 'cost_money' => 0, 'subsidy_money' => 0, 'earnest_money' => 0, 'refund_money' => 0];
    }

    /**
     * 已买引流券列表
     *
     * @param $data
     * @return array
     */
    public static function myITCouponList($data)
    {
        $page = !isset($data['page']) ? 1 : $data['page'];
        unset($data['page']);
        $limit = !isset($data['limit']) ? 10 : $data['limit'];
        unset($data['limit']);

        //已买的引流券id
        $couponArr = DB::table(CouponStore::table)->select('coupon_id', 'redeem_code')->where('shop_id', '=', $data['store_id'])->get()->toArray();
        if (empty($couponArr)) {
            return [];
        }
        $couponIds = array_column($couponArr, 'coupon_id');
        $couponArr = array_combine($couponIds, $couponArr);

        $where_data = [];
        $where_data[] = [function ($query) use ($couponIds) {
            $query->whereIn('id', $couponIds);
        }];
        $where_data[] = ['is_deleted', '=', Coupon::NOT_DELETE];
        $where_data[] = ['type', '=', Coupon::TYPE_UNIVERSAL];
        $select = ['id', 'name', 'coupon_type', 'category', 'satisfy_money', 'remitted_money', 'use_limit_max', 'price', 'content'];

        $list = Coupon::listed($page, $limit, $where_data, $select);
        foreach ($list['data'] as $v) {
            $v->redeem_code = empty($couponArr[$v->id]) ? '' : $couponArr[$v->id]->redeem_code;
            $v->use_number = CouponUseLog::getUseNumber(['coupon_id' => $v->id, 'shop_id' => $data['store_id'], 'is_use' => CouponUseLog::IS_USE]);
        }

        return $list;
    }

    /**
     * 购买引流券
     *
     * @param $data
     * @return array
     * @throws InvalidRequestException
     */
    public static function buyITCoupon($data)
    {
        if(empty($data['info'])){
            throw new InvalidRequestException(40001);
        }
        $addArr = [];
        foreach ($data['info'] as $v) {
            $arrArr[] = [
                'coupon_id' => $v['coupon_id'],
                'shop_id' => $data['shop_id'],
                'money' => $v['money'],
                'number' => $v['number'],
                'status' => CouponStore::STATUS_WAIT,
            ];
        }

        $return = CouponStore::insertData($addArr);

        return $return;
    }

    /**
     * 使用记录
     *
     * @param $data
     * @return array
     */
    public static function getUseLog($data)
    {

        $page = !isset($data['page']) ? 1 : $data['page'];
        unset($data['page']);
        $limit = !isset($data['limit']) ? 10 : $data['limit'];
        unset($data['limit']);

        $where_data = [];
        $where_data[] = ['shop_id', '=', $data['store_id']];
        $where_data[] = ['is_use', '=', CouponUseLog::IS_USE];
        if (!empty($data['type'])) {
            $where_data[] = ['type', '=', $data['type']];
        }
        if (!empty($data['coupon_id'])) {
            $where_data[] = ['coupon_id', '=', $data['coupon_id']];
        }
        $list = CouponUseLog::listed($page, $limit, $where_data);
        if (empty($list['data'])) {
            return $list;
        }
        //取出所有卡券id查询卡券信息
        $couponIds = array_column($list['data'], 'coupon_id');
        $couponArr = DB::table(Coupon::table)->select('id', 'name', 'coupon_type', 'category', 'satisfy_money', 'remitted_money', 'use_limit_max', 'price', 'content')->whereIn('id', $couponIds)->get()->toArray();
        $keys = array_column($couponArr, 'id');
        $couponArr = array_combine($keys, $couponArr);

        foreach ($list['data'] as $v) {
            $v->verification_at = $v->verification_at ? date('Y-m-d H:i:s', $v->verification_at) : '';
            $v->name = empty($couponArr[$v->coupon_id]) ? '' : $couponArr[$v->coupon_id]->name;
            $v->coupon_type = empty($couponArr[$v->coupon_id]) ? '' : $couponArr[$v->coupon_id]->coupon_type;
            $v->category = empty($couponArr[$v->coupon_id]) ? '' : $couponArr[$v->coupon_id]->category;
            $v->satisfy_money = empty($couponArr[$v->coupon_id]) ? '' : $couponArr[$v->coupon_id]->satisfy_money;
            $v->remitted_money = empty($couponArr[$v->coupon_id]) ? '' : $couponArr[$v->coupon_id]->remitted_money;
            $v->use_limit_max = empty($couponArr[$v->coupon_id]) ? '' : $couponArr[$v->coupon_id]->use_limit_max;
            $v->content = empty($couponArr[$v->coupon_id]) ? '' : $couponArr[$v->coupon_id]->content;
            //订单


        }

        return $list;
    }

    /**
     * 设置停售
     *
     * @param $data
     * @return array
     */
    public static function haltSales($data)
    {
        $where[] = ['coupon_id', '=', $data['coupon_id']];
        $where[] = ['shop_id', '=', $data['shop_id']];
        $update = ['status' => CouponStore::STATUS_HALT_SALE];
        $return  = CouponStore::updatedData($where,$update);
        return $return;
    }

    /**
     * 专用券总量
     *
     * @param $data
     * @return array
     */
    public static function couponTotal($data)
    {
        //总发放
        $send_number = CouponUseLog::getUseNumber(['type' => Coupon::TYPE_DEDICATED, 'shop_id' => $data['store_id']]);
        //已过期
        $overdue_number = CouponUseLog::getUseNumber(['type' => Coupon::TYPE_DEDICATED, 'shop_id' => $data['store_id'], ['use_time_end', '<', time()]]);
        //已使用
        $use_number = CouponUseLog::getUseNumber(['type' => Coupon::TYPE_DEDICATED, 'shop_id' => $data['store_id'], 'is_use' => CouponUseLog::IS_USE]);
        //使用率
        $use_rate = empty($send_number) ? 0 : ($use_number / $send_number * 100);
        return ['send_number' => $send_number, 'overdue_number' => $overdue_number, 'use_number' => $use_number, 'use_rate' => $use_rate];
    }

    /**
     * 专用券列表
     *
     * @param $data
     * @return array
     */
    public static function couponLists($data)
    {
        $page = !isset($data['page']) ? 1 : $data['page'];
        unset($data['page']);
        $limit = !isset($data['limit']) ? 10 : $data['limit'];
        unset($data['limit']);

        $where_data = [];
        $where_data[] = ['type', '=', Coupon::TYPE_DEDICATED];
        $where_data[] = ['is_deleted', '=', Coupon::NOT_DELETE];
        $where_data[] = ['shop_id', '=', $data['store_id']];
        $select = ['id', 'name', 'coupon_type', 'category', 'satisfy_money', 'remitted_money', 'confine_type', 'confine_id', 'except_type', 'except_id', 'use_time_start', 'use_time_end', 'stock', 'content'];

        $list = Coupon::listed($page, $limit, $where_data, $select);

        foreach($list['data'] as $v){
            $v->use_time_start = empty($v->use_time_start) ? '' : date('Y-m-d', $v->use_time_start);
            $v->use_time_end = empty($v->use_time_end) ? '' : date('Y-m-d', $v->use_time_end);
            //购买数量 已用数量
            $v->send_number = CouponUseLog::getUseNumber(['coupon_id' => $v->id]);
            $v->use_number = CouponUseLog::getUseNumber(['coupon_id' => $v->id, 'is_use' => 1]);
        }
        return $list;
    }

    /**
     * 添加编辑专用券
     *
     * @param $data
     * @return array
     */
    public static function modifyCoupon($data)
    {
        if (empty($data) && $data == false) {
            return [];
        }

        // 可领取时间方式 1时间段
        if ($data['get_time_type'] == 1) {
            if ($data['get_time_start'] == false || $data['get_time_end'] == false) {
                errorJson('可领取时间段必须填写!', []);
            }
            $data['get_time_start'] = strtotime($data['get_time_start'].' 00:00:00');
            $data['get_time_end'] = strtotime($data['get_time_end'].' 23:59:59');
        }

        $data['type'] = Coupon::TYPE_DEDICATED;
        $data['use_time_start'] = strtotime($data['use_time_start'].' 00:00:00');
        $data['use_time_end'] = strtotime($data['use_time_end'].' 23:59:59');

        $id = !empty($data['id']) ? $data['id'] : 0;
        unset($data['id']);

        if ($id) {
            $data['updated_at'] = time();
            $list = Coupon::updatedData($id, $data);
        } else {
            $data['created_at'] = time();
            $list = Coupon::insertData($data);
            //添加
            $addArr = [
                'coupon_id' => $list,
                'shop_id' => $data['shop_id'],
                'money' => $data['remitted_money'],
                'number' => $data['stock'],
                'status' => CouponStore::STATUS_WAIT,
                ];
            $return = CouponStore::insertData($addArr);
        }

        return $list;
    }

    /**
     * 专用券详情
     *
     * @param $data
     * @return array
     */
    public static function getDedicatedCouponDetail($data)
    {
        if (empty($data) && $data == false) {
            return [];
        }

        $data['id'] = !empty($data['id']) ? $data['id'] : 0;
        $data['type'] = Coupon::TYPE_DEDICATED;
        $data['is_deleted'] = Coupon::NOT_DELETE;

        $list = Coupon::detail($data);

        //处理数据
        $returnData['id'] = $list->id;
        $returnData['name'] = $list->name;
        $returnData['coupon_type'] = $list->coupon_type;
        $returnData['shop_id'] = $list->shop_id;

        $shop = explode(',', $list->shop_id);
        $shopNameArr = CouponUseLog::getShopName($shop);
        $k = array_column($shopNameArr, 'id');
        $shopNameArr = array_combine($k, $shopNameArr);
        $shopName = [];
        foreach($shop as $shop_id){
            $shopName[] = !empty($shopNameArr[$shop_id]) ? $shopNameArr[$shop_id]['name'] : '暂无数据';
        }
        $returnData['shop_name'] = $shopName;//

        $returnData['satisfy_money'] = $list->satisfy_money;
        $returnData['remitted_money'] = $list->remitted_money;
        $returnData['stock'] = $list->stock;
        $returnData['get_type'] = $list->get_type;
        $returnData['price'] = $list->price;
        $returnData['confine_type'] = $list->confine_type;
        $returnData['confine_id'] = $list->confine_id;

        $confineIds = explode(',', $list->confine_id);
        switch($list->confine_type) {
            case 1:
                $returnData['confine_name'] = ['全场通用'];
                break;
            case 2: //商品
                $goodsName = CouponUseLog::getGoodsName($confineIds);
                $returnData['confine_name'] = array_column($goodsName, 'name');
                break;
            case 3: //分类
                $categoryName = CouponUseLog::getCategoryName($confineIds);
                $returnData['confine_name'] = array_column($categoryName, 'name');
                break;
            case 4: //分组
                $groupName = CouponUseLog::getGroupName($confineIds);
                $returnData['confine_name'] = array_column($groupName, 'name');
                break;
            default:
                $returnData['confine_name'] = [];
                break;
        }

        $returnData['except_type'] = $list->except_type;
        $returnData['except_id'] = $list->except_id;


        $exceptIds = explode(',', $list->except_id);
        switch($list->confine_type) {
            case 1:
                $returnData['except_name'] = ['全场通用'];
                break;
            case 2: //商品
                $goodsName = CouponUseLog::getGoodsName($exceptIds);
                $returnData['except_name'] = array_column($goodsName, 'name');
                break;
            case 3: //分类
                $categoryName = CouponUseLog::getCategoryName($exceptIds);
                $returnData['except_name'] = array_column($categoryName, 'name');
                break;
            case 4: //分组
                $groupName = CouponUseLog::getGroupName($exceptIds);
                $returnData['except_name'] = array_column($groupName, 'name');
                break;
            default:
                $returnData['except_name'] = [];
                break;
        }

        $returnData['get_time_type'] = $list->get_time_type;
        $returnData['get_time_start'] = empty($list->get_time_start) ? '' : date('Y-m-d H:i', $list->get_time_start);
        $returnData['get_time_end'] = empty($list->get_time_end) ? '' : date('Y-m-d H:i', $list->get_time_end);
        $returnData['use_time_start'] = empty($list->use_time_start) ? '' : date('Y-m-d H:i', $list->use_time_start);
        $returnData['use_time_end'] = empty($list->use_time_end) ? '' : date('Y-m-d H:i', $list->use_time_end);
        $returnData['get_limit_max'] = $list->get_limit_max;
        $returnData['is_open'] = $list->is_open;
        $returnData['use_limit_max'] = $list->use_limit_max;
        $returnData['content'] = $list->content;

        return $returnData;
    }

    /**
     * 删除 - 卡券
     *
     * @param $data //请求参数数组
     * @return array
     */
    public static function updateStatus($data)
    {
        if (empty($data) && $data == false) {
            return [];
        }

        $data['id'] = !empty($data['id']) ? $data['id'] : 0;
        $update_data['is_deleted'] = !empty($data['is_deleted']) ? $data['is_deleted'] : Coupon::IS_DELETE;
        unset($data['is_deleted']);
        $update_data['deleted_at'] = time();

        $list = Coupon::deleteds($data, $update_data);
        return $list;
    }
}